using AutoMapper;
using B.S.BaseData.Domain;
using MediatR;
using SmartTracking.API.Write.Application.Commands.Purchasing.Eliminates;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Write.Application.CommandHandlers.Purchasing.Eliminates
{
    public class UpdateEliminateCommandHandler : IRequestHandler<UpdateEliminateCommand, ApiResult<int>>
    {

        private readonly IBaseRepository<Eliminate> eliminate;
        private readonly IMapper map;

        public UpdateEliminateCommandHandler(IBaseRepository<Eliminate> eliminate, IMapper map)
        {
            this.eliminate = eliminate;
            this.map = map;
        }

        public async Task<ApiResult<int>> Handle(UpdateEliminateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            try
            {
                // 获取要更新的淘汰记录
                var existingEliminate = await eliminate.GetByIdAsync(request.EliminateId);
                
                if (existingEliminate == null || existingEliminate.IsDeleted)
                {
                    res.Message = "淘汰记录不存在或已删除";
                    res.Code = ApiEnum.更新失败;
                    return res;
                }

                // 使用AutoMapper将请求映射到现有实体
                map.Map(request, existingEliminate);

                // 执行更新操作
                int r = await eliminate.UpdateAsync(existingEliminate);

                if (r > 0)
                {
                    res.Message = "更新成功";
                    res.Code = ApiEnum.更新成功;
                    res.data = r;
                }
                else
                {
                    res.Message = "更新失败";
                    res.Code = ApiEnum.更新失败;
                }
            }
            catch (Exception ex)
            {
                res.Message = "更新失败: " + ex.Message;
                res.Code = ApiEnum.更新失败;
            }

            return res;
        }
    }
}
